package com.mzw.project.service.impl.inner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mzw.mzwcommon.model.entity.InterfaceInfo;
import com.mzw.mzwcommon.service.InnerInterfaceInfoService;
import com.mzw.project.common.ErrorCode;
import com.mzw.project.exception.BusinessException;
import com.mzw.project.mapper.InterfaceInfoMapper;
import com.mzw.project.service.InterfaceInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;

/**
 * @author L1nAn
 */
@DubboService
public class InnerInterfaceInfoServiceImpl implements InnerInterfaceInfoService {

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public InterfaceInfo getInterfaceInfo(String url, String method) {
        if (StringUtils.isAnyBlank(url, method)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("url", url);
        queryWrapper.eq("method", method);
        return interfaceInfoMapper.selectOne(queryWrapper);

    }

    @Override
    public boolean addNum(long interfaceInfoId) {
        boolean isAdd = interfaceInfoMapper.addNum(interfaceInfoId);
        if (isAdd) {
            // 成功才能入Zset
            String key = "interfaceInfoId";
            Double score = stringRedisTemplate.opsForZSet().score(key, String.valueOf(interfaceInfoId));
            // 如果分数为空
            if (score == null) {
                stringRedisTemplate.opsForZSet().add(key, String.valueOf(interfaceInfoId)
                        , interfaceInfoService.getById(interfaceInfoId).getTotalNums());
            }else {
                stringRedisTemplate.opsForZSet().incrementScore(key, String.valueOf(interfaceInfoId), 1);
            }
        }
        return isAdd;
    }
}
